package com.yzt.message;

import android.app.Application;
import android.os.Handler;
import android.os.Looper;

import androidx.lifecycle.MutableLiveData;

import com.yzt.p_base.utils.ThreadCenter;
import com.yzt.message.conversation.ReceiptHandlerContainer;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import io.rong.common.RLog;
import io.rong.imkit.conversationlist.model.BaseUiConversation;
import io.rong.imkit.conversationlist.model.GroupConversation;
import io.rong.imkit.conversationlist.model.SingleConversation;
import io.rong.imkit.event.Event;
import io.rong.imkit.widget.refresh.constant.RefreshState;
import io.rong.imlib.IRongCoreCallback;
import io.rong.imlib.IRongCoreEnum;
import io.rong.imlib.RongCoreClient;
import io.rong.imlib.model.Conversation;

public class MessageListViewModel extends CustomConversationListViewModel {

    private final String TAG = MessageListViewModel.class.getSimpleName();
    private boolean isTaskScheduled;
    protected Handler mHandler;
    protected long mLastSyncTime;

    public MessageListViewModel(Application application) {
        super(application);
        this.mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void getConversationList(boolean loadMore) {
        getConversationList(loadMore, loadMore);
    }

    public void getConversationList(final boolean loadMore, final boolean isEventManual) {
        if (!this.isTaskScheduled) {
            this.isTaskScheduled = true;
            this.mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    MessageListViewModel.this.isTaskScheduled = false;
                    ((MutableLiveData<Event.RefreshEvent>) getRefreshEventLiveData()).postValue(new Event.RefreshEvent(RefreshState.LoadFinish));

                    RongCoreClient.getInstance().getConversationList(new IRongCoreCallback.ResultCallback<List<Conversation>>() {

                        @Override
                        public void onCallback(List<Conversation> conversations) {
                            ThreadCenter.postNormalThread(() -> onSuccess(conversations));
                        }

                        @Override
                        public void onSuccess(List<Conversation> conversations) {

                            if (isEventManual) {
                                if (loadMore) {
                                    ((MutableLiveData) getRefreshEventLiveData()).postValue(new Event.RefreshEvent(RefreshState.LoadFinish));
                                } else {
                                    ((MutableLiveData) getRefreshEventLiveData()).postValue(new Event.RefreshEvent(RefreshState.RefreshFinish));
                                }
                            }

                            if (conversations != null && conversations.size() != 0) {
                                RLog.d(MessageListViewModel.this.TAG, "getConversationListByPage. size:" + conversations.size());
                                MessageListViewModel.this.mLastSyncTime = conversations.get(conversations.size() - 1).getSentTime();
                                List<Conversation> copyList = new CopyOnWriteArrayList(conversations);
                                for (Conversation conversation : copyList) {
                                    if (conversation.getTargetId().equals(MessageConstants.TYPE_NOMI_SERVICE)) {
                                        conversation.setTop(true);
                                    }
                                    if (conversation.getConversationType().equals(Conversation.ConversationType.CHATROOM)) {
                                        continue;
                                    }
                                    BaseUiConversation oldItem = findConversationFromList(conversation.getConversationType(), conversation.getTargetId(), false);
                                    if (oldItem != null) {
                                        oldItem.onConversationUpdate(conversation);
                                    } else if (conversation.getConversationType().equals(Conversation.ConversationType.GROUP)) {
                                        MessageListViewModel.this.mUiConversationList.add(new GroupConversation(MessageListViewModel.this.mApplication.getApplicationContext(), conversation));
                                    } else {
                                        BaseUiConversation uiConversation = new SingleConversation(MessageListViewModel.this.mApplication.getApplicationContext(), conversation);
                                        MessageListViewModel.this.mUiConversationList.add(uiConversation);
                                    }
                                }

                                // ReceiptHandlerContainer.getInstance().handleReceipts(mUiConversationList);
                                MessageListViewModel.this.sort();
                                MessageListViewModel.this.mConversationListLiveData.postValue(MessageListViewModel.this.mUiConversationList);
                            }
                        }

                        @Override
                        public void onError(IRongCoreEnum.CoreErrorCode coreErrorCode) {
                            if (loadMore) {
                                ((MutableLiveData) getRefreshEventLiveData()).postValue(new Event.RefreshEvent(RefreshState.LoadFinish));
                            } else {
                                ((MutableLiveData) getRefreshEventLiveData()).postValue(new Event.RefreshEvent(RefreshState.RefreshFinish));
                            }
                        }
                    }, MessageListViewModel.this.mSupportedTypes);
                }
            }, 500L);
        }
    }

    public CopyOnWriteArrayList<BaseUiConversation> getUiConversationList() {
        return MessageListViewModel.this.mUiConversationList;
    }
}
